package crawler;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Iterator;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.util.EntityUtils;

public class Bzhanjson {
	//url json解析 获得真是视频地址
	public static String jsontostring(String url) {
		String url2="";
		DefaultHttpClient httpclient = new DefaultHttpClient(new PoolingClientConnectionManager());
		    HttpGet httpget = new HttpGet(url);  
		     CloseableHttpResponse response = null;  
		   /* HttpClientBuilder build = HttpClients.custom();  
		      HttpHost proxy = new HttpHost("127.0.0.1", 1080);  
		        CloseableHttpClient client = build.setProxy(proxy).build(); */
		     HttpEntity entity = null;
		     String s="";
		     try {
		           httpget.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0");
		        httpget.addHeader("Host","api.bilibili.com");
		         httpget.addHeader("Cookie", "buvid3=");
		        // httpget.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		         //httpget.addHeader("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
		        // httpget.addHeader("Accept-Encoding","gzip, deflate, br");
		        // httpget.addHeader("Connection","keep-alive");
		       //  httpget.addHeader("Pragma","no-cache");
		        // httpget.addHeader("If-None-Match","6f893c5bff8c1b19835a82bd12c290ae");
		        response = httpclient.execute(httpget);
		     //   System.out.println(response.getHeaders("Cookie").toString());
		       entity = response.getEntity(); 
		     // System.out.println("doGet"+response.getStatusLine().getStatusCode());
		        url2 = EntityUtils.toString(entity, "UTF-8");
		       String[] s1=url2.replace("\"", "").split(",");
		       for (String string : s1) {
		    	   if(string.split(":")[0].equals("url")) {
		    		   url2=string.split(":")[1]+":"+string.split(":")[2];
		    		 url2=  url2.replace("\\", "").replace("}", "").replace("]", "");
		    	   }
				
			}
		    } catch (ClientProtocolException e) {
		        e.printStackTrace();
		    } catch (IOException e) {
		        e.printStackTrace();
		    }finally {
		        httpclient.close();
		       
		    }
		
		return url2;
	}
	//下载视频
	public static void download(String url) throws FileNotFoundException {
			
			File dest1 = new File("E:/vi");
		   	 if  (!dest1 .exists()  && !dest1 .isDirectory())      
		   	 {       
		   	     dest1 .mkdir();    
		   	 } 
		   	File dest = new File("E:/vi/"+new Date().getTime()+".mp4");
		   	 if(!dest.exists())    
		   	 {    
		   	     try {    
		   	    	 dest.createNewFile();    
		   	     } catch (IOException e) {    
		   	     }    
		   	 }  
		        InputStream is;
		        FileOutputStream fos = new FileOutputStream(dest);
		        URL temp;
				try {
					temp = new URL(url.trim());
					 URLConnection uc = temp.openConnection();
					 uc.addRequestProperty("User-Agent", "Mozilla/5.0 (iPad; U; CPU OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5");
					is = temp.openStream();
			         BufferedInputStream bis = new BufferedInputStream(is);
			         BufferedOutputStream bos = new BufferedOutputStream(fos);
			         int length;
			         byte[] bytes = new byte[1024*20];
			         while((length = bis.read(bytes, 0, bytes.length)) != -1){
			             fos.write(bytes, 0, length);
			         }
			         bos.close();
			         fos.close();
			         bis.close();
			         is.close();

				} catch (Exception e) {
				}
		
	}
public static void main(String[] args) throws Exception {
	//测试 以后改成从文本读取
	String url="https://api.bilibili.com/playurl?callback=callbackfunction&aid=16121383&page=1&platform=html5&quality=1&vtype=mp4&type=json&token=5ec90a52daa6eb3de19ea732c518c741";
	System.out.println(jsontostring(url));
	download(jsontostring(url));
}

}
